package com.itheima.springbootsecurity.handler;

import com.alibaba.fastjson2.JSON;
import com.itheima.springbootsecurity.domain.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 已登录用户，但无权限访问资源的处理器
 * @author wuhaohua
 */
@Component
public class CustomAccessDeniecHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置客户端的响应的内容类型
        response.setContentType("application/json;charset=UTF-8");
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 获取返回值的json字符串
        String resultJson = JSON.toJSONString(Result.error("无访问权限，请联系管理员！"));
        // 将json对象写到输出流中
        outputStream.write(resultJson.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
